﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YQBlog.Models;
using System.Web.Routing;
using Common;
using System.Configuration;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Text;
using Ninject;
using YQBlog.General;
using res = Resource.Controllers.Admin.Admin;
using System.Web.Security;
using HtmlAgilityPack;

namespace YQBlog.Controllers
{
    [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
        [Inject]
        public IServices myService { get; set; }

        GeneralConfigInfo configinfo = YQBlog.General.WebUtils.configinfo;

        public ActionResult Index()
        {
            SiteInfo siteinfo = new SiteInfo();
            string re = "";
            try
            {
                re = Utils.GetFileSource("/content/site.htm");
            }
            catch (Exception) { re = ""; }
            HtmlNode logoNode = null;
            HtmlNode descriptionNode = null;
            HtmlNode countryNode = null;
            HtmlNode tagsNode = null;
            if (re != "")
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(re);
                logoNode = doc.GetElementbyId("logo");
                countryNode = doc.GetElementbyId("country");
                tagsNode = doc.GetElementbyId("tags");
                descriptionNode = doc.GetElementbyId("description");
            }
            siteinfo.Name = configinfo.Webtitle;
            siteinfo.Url = configinfo.Weburl;
            siteinfo.Tags = "";
            siteinfo.Logo = "";
            siteinfo.Description = "";
            siteinfo.Country = "";
            if (logoNode != null)
                siteinfo.Logo = logoNode.InnerText!=""?logoNode.InnerText:configinfo.Logo;
            if (countryNode != null)
                siteinfo.Country = countryNode.InnerText;
            if (tagsNode != null)
                siteinfo.Tags = tagsNode.InnerText;
            if (descriptionNode != null)
                siteinfo.Description = descriptionNode.InnerHtml != "" ? descriptionNode.InnerHtml : configinfo.WebDescription;
            return View("AdminIndex", siteinfo);
        }

        /// <summary>
        /// 文章列表
        /// </summary>
        public ActionResult AdminArticle(int? p,int? tid,int? layer,int? cid,string sort,string order)
        {
            
            Pager pager = new Pager();
            int typeid = tid ?? 0;
            int layerid = layer ?? 0;
            int cateid = cid ?? 0;
            pager.PageNo = p ?? 1;
            pager.PageSize = 20;
            if(cateid>0)
                pager = myService.GetReplyPaging(pager, typeid, myService.GetCategoryIds(cateid), layerid, sort, WebUtils.MyString(order,"desc"));
            else
                pager = myService.GetReplyPaging(pager, typeid, cateid, layerid, sort, WebUtils.MyString(order,"desc"));
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.TypeId = typeid;
            ViewBag.LayerId = layerid;
            ViewBag.Cid = cateid;
            ViewBag.Sort = sort;
            ViewBag.Order = order;
            List<CategoryModel> catelist=myService.getFCategoryList(typeid.ToString(), "", " -- ");
            catelist.Insert(0, new CategoryModel
            {
                CateId = "0",
                CateName = res.SelectSubcategories
            });
            ViewBag.CurrentItem = layerid>0?"l"+layerid.ToString():"t"+typeid.ToString();
            ViewData["CateId"] = new SelectList(catelist, "CateId", "CateName", cateid);
            return View(pager.Entity);
        }
        
        /// <summary>
        /// 新增文章
        /// </summary>
        public ActionResult AdminAdd(string tid,string cid)
        {
            ViewData["CateId"] = new SelectList(myService.getFCategoryList(tid, ""," -- "), "CateId", "CateName",cid);
            ViewBag.CurrentItem = "t" + tid;
            if (tid == "4")
                return View("AdminAlbumAdd");

            return View();
        }
  
        /// <summary>
        /// 新增文章（提交）
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AdminAdd(ArticleModel model)
        {
            if (ModelState.IsValid)
            {
                blog_varticle obj = InitialArticleModel.VArticle();
                CategoryModel category = myService.GetCategoryByID(model.CateId);
                obj.typeid = Utils.StrToInt(category.Type);
                obj.cateid = model.CateId;
                obj.catepath = category.Path; ;
                obj.title = Utils.FileterStr(model.Title);
                obj.summary = Server.UrlDecode(WebUtils.MyString(model.Summary));
                obj.content = Server.UrlDecode(Utils.DownloadImages(model.Content, "/Content/Upload/", configinfo.Weburl));
                obj.tags = WebUtils.MyString(model.Tags).Trim();
                obj.seodescription = Utils.RemoveHtml(WebUtils.MyString(model.SeoDescription)).Trim();
                obj.seokeywords = Utils.RemoveHtml(WebUtils.MyString(model.Seokeywords)).Trim();
                obj.seometas = WebUtils.MyString(model.SeoMetas);
                obj.seotitle = Utils.RemoveHtml(WebUtils.MyString(model.SeoTitle)).Trim();
                obj.rename = Utils.RemoveHtml(WebUtils.MyString(model.ReName)).Trim();
                obj.userid = 1;
                obj.username = User.Identity.Name;
                obj.replypermit = model.ReplyPermit;
                obj.status = model.Status;
                obj.iscommend = model.IsCommend;
                obj.istop = model.IsTop;

                int re=myService.AddArticle(obj);
                if (configinfo.IfHtmlCreated == 1)
                    WebUtils.CreateHtml(obj.typeid,re, obj.rename, obj.createdate);

                return RedirectToAction("AdminArticle", new { tid = obj.typeid, cid = obj.cateid });
            }
            return View(model);
        }

        /// <summary>
        /// 文章修改
        /// </summary>
        public ActionResult AdminEdit(int id)
        {
            blog_varticle obj = new blog_varticle();
            obj = myService.GetVArticleByID(id);
            ArticleModel model = new ArticleModel();
            model.ID = obj.id;
            model.CateId = obj.cateid;
            model.Title = Utils.FileterStr(obj.title);
            model.Summary = WebUtils.MyString(obj.summary);
            model.Content = WebUtils.MyString(obj.content);
            model.Tags = WebUtils.MyString(obj.tags);
            model.SeoDescription = WebUtils.MyString(obj.seodescription);
            model.Seokeywords = WebUtils.MyString(obj.seokeywords);
            model.SeoMetas = WebUtils.MyString(obj.seometas);
            model.SeoTitle = WebUtils.MyString(obj.seotitle);
            model.ReName = WebUtils.MyString(obj.rename);
            model.Status = obj.status;
            model.ReplyPermit = obj.replypermit;
            model.IsCommend = obj.iscommend;
            model.IsTop = obj.istop;
            model.CreateDate = obj.createdate;
            ViewBag.CurrentItem = "t" + obj.typeid;
            ViewData["CateId"] = new SelectList(myService.getFCategoryList(obj.typeid.ToString(),""," -- "), "CateId", "CateName", model.CateId);
            //相册修改
            if (obj.typeid == 4)
                return View("AdminAlbumEdit", model);
            return View(model);
        }

        /// <summary>
        /// 提交文章修改
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AdminEdit(ArticleModel model)
        {
            if (ModelState.IsValid)
            {
                blog_varticle obj = InitialArticleModel.VArticle();
                CategoryModel category = myService.GetCategoryByID(model.CateId);
                obj.id = model.ID;
                obj.typeid = Utils.StrToInt(category.Type);
                obj.cateid = model.CateId;
                obj.catepath = category.Path;
                obj.title = Utils.FileterStr(model.Title);
                obj.summary = Utils.FileterStr(Server.UrlDecode(model.Summary));
                obj.content = Utils.FileterStr(Server.UrlDecode(Utils.DownloadImages(model.Content, "/Content/Upload/", configinfo.Weburl)));
                obj.ip = Utils.GetIP();
                obj.tags = WebUtils.MyString(model.Tags).Trim();
                obj.replypermit = model.ReplyPermit;
                obj.seodescription = Utils.RemoveHtml(WebUtils.MyString(model.SeoDescription)).Trim();
                obj.seokeywords = Utils.RemoveHtml(WebUtils.MyString(model.Seokeywords)).Trim();
                obj.seometas = WebUtils.MyString(model.SeoMetas);
                obj.seotitle = Utils.RemoveHtml(WebUtils.MyString(model.SeoTitle)).Trim();
                obj.rename = Utils.RemoveHtml(WebUtils.MyString(model.ReName)).Trim();
                obj.status = model.Status;
                obj.userid = 1;
                obj.username = User.Identity.Name;
                obj.iscommend = model.IsCommend;
                obj.istop = model.IsTop;
                myService.UpdateVArticle(obj);

                if (configinfo.IfHtmlCreated == 1)
                    WebUtils.CreateHtml(obj.typeid,obj.id, obj.rename, model.CreateDate);

                return RedirectToAction("AdminArticle", new { tid = obj.typeid, cid = obj.cateid });
            }
            return View(model);
        }

        /// <summary>
        /// 文章删除
        /// </summary>
        [HttpPost]
        public ActionResult AdminDel(int id, int parentid)
        {
            try
            {
                blog_article obj = new blog_article();
                obj.id = id;
                obj.parentid = parentid;
                if (parentid == 0)
                {
                    blog_varticle varticle = new blog_varticle();
                    varticle = myService.GetVArticleByID(id);
                    myService.DelArticle(obj);
                    WebUtils.DeleteHtml(varticle.id, varticle.rename, varticle.createdate);
                }
                else
                {
                    myService.DelArticle(obj);
                }
            }
            catch (Exception)
            {
                return Content(res.DeleteFailed, "text/html;charset=UTF-8");
            }
            return Content(res.DeletedSuccessfully, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 分类配置管理
        /// </summary>
        public ActionResult AdminCategory()
        {
            ViewBag.Content = myService.GetCategoryStr();
            return View();
        }

        /// <summary>
        /// 提交分类配置（手动修改）
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AdminCategory(string content)
        {
            try
            {
                List<CategoryModel> lst = Utils.ParseFromJson<List<CategoryModel>>(content);
                List<CategoryModel> newlst = RefreshCateList(lst);
                SaveCateInfo(newlst);
            }
            catch (Exception)
            {
                return Content(res.ModificationFailed + "<a href=\"/BlogAdmin/admin/AdminCategory\">" + res.ContinueModify + "</a>", "text/html;charset=UTF-8");
            }
            return Content(res.ModifiedSuccessfully + " <a href=\"/BlogAdmin/admin/AdminCategory\">" + res.ContinueModify + "</a>", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 刷新catelist，更新subcuont,path字段
        /// </summary>
        public List<CategoryModel> RefreshCateList(List<CategoryModel> lst)
        {
            List<CategoryModel> newlst = new List<CategoryModel>();
            foreach (CategoryModel c in lst)
            {
                CategoryModel category = new CategoryModel();
                category = c;
                category.Path = GetCategoryPath(lst, category);
                category.SubCount = GetSubCount(lst, category.CateId).ToString();
                newlst.Add(category);
            }
            return newlst;
        }

        /// <summary>
        /// 保存分类信息到json
        /// </summary>
        public void SaveCateInfo(List<CategoryModel> lst)
        {
            List<CategoryModel> newlst = new List<CategoryModel>();
            List<CategoryLangModel> langlst = new List<CategoryLangModel>();
            if (Resource.Models.Web.Web.Lang != configinfo.DefaultLang)
            {
                string jsonnavlang = Utils.GetFileSource("/Content/js/Category.Lang." + configinfo.DefaultLang + ".js").Replace("var categorylang =", "").Trim().Replace("\n", "");
                if (jsonnavlang != "")
                {
                    langlst = Utils.ParseFromJson<List<CategoryLangModel>>(jsonnavlang);
                }

                newlst = (from a in lst
                          join b in langlst
                          on a.CateId equals b.CateId into temp
                          from t in temp.DefaultIfEmpty()
                          select new CategoryModel
                          {
                              CateId = a.CateId,
                              CateName = t == null ? a.CateName : t.CateName,
                              Type = a.Type,
                              ListNum = a.ListNum,
                              ReplyPermit = a.ReplyPermit,
                              ParentId = a.ParentId,
                              IsNav = a.IsNav,
                              IsIndex = a.IsIndex,
                              Status = a.Status,
                              ReName = a.ReName,
                              CustomView = t == null ? a.CustomView : t.CustomView,
                              SubCount = a.SubCount,
                              OrderId = a.OrderId,
                              Path = a.Path
                          }).ToList();
            }
            else
                newlst = lst;

            string jsonstr = Utils.GetJson<List<CategoryModel>>(newlst);
            string file = System.Web.HttpContext.Current.Server.MapPath("/Content/js/Category.js");

            using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
            {
                writer.Write("var category = " + jsonstr);
            }
            SaveCateLangInfo(lst);
            RefreshConfigVersionNo();
        }

        /// <summary>
        /// 保存分类语言信息到json
        /// </summary>
        public void SaveCateLangInfo(List<CategoryModel> lst)
        {
            List<CategoryLangModel> lstlang = (from p in lst select new CategoryLangModel { CateId = p.CateId, CateName = p.CateName, CustomView = p.CustomView }).ToList();
            string jsonstr = Utils.GetJson<List<CategoryLangModel>>(lstlang);
            string file = System.Web.HttpContext.Current.Server.MapPath("/Content/js/" + WebUtils.GetCategoryLangName());

            using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
            {
                writer.Write("var categorylang = " + jsonstr);
            }
        }

        /// <summary>
        /// 计算当前分类的子分类数
        /// </summary>
        private int GetSubCount(List<CategoryModel> lst, string parent)
        {
            int total = 0;
            foreach (CategoryModel c in lst)
            {
                if (c.ParentId == parent)
                    total++;
            }
            return total;
        }

        /// <summary>
        /// 计算当前分类的path
        /// </summary>
        private string GetCategoryPath(List<CategoryModel> lst, CategoryModel category)
        {
            CategoryModel c = category;
            string path = GetCurrentCategoryUrl(c);
            while (c.ParentId != "0")
            {
                foreach (CategoryModel cc in lst)
                {
                    if (cc.CateId == c.ParentId)
                    {
                        path = GetCurrentCategoryUrl(cc) + path;
                        c = cc;
                        continue;
                    }
                }
            }
            return path.Trim(',');
        }

        private string GetCurrentCategoryUrl(CategoryModel category)
        {
            return "," + category.CateId;
        }

        /// <summary>
        /// 转载网站json配置修改
        /// </summary>
        public ActionResult AdminPublishWebConfig()
        {
            ViewBag.Content = myService.GetPublishWebStr();
            return View();
        }

        /// <summary>
        /// 提交转载网站json配置修改
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AdminPublishWebConfig(string content)
        {
            try
            {
                List<PublishWebModel> lst = Utils.ParseFromJson<List<PublishWebModel>>(content);
                string jsonstr = Utils.GetJson<List<PublishWebModel>>(lst);
                string file = System.Web.HttpContext.Current.Server.MapPath("/Content/js/PublishWeb.js");
                using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
                {
                    writer.Write(jsonstr);
                }
                DataCache.SetCache("Json-PublishWeb", jsonstr, DateTime.Now.AddMinutes(180.0), TimeSpan.Zero);
                RefreshConfigVersionNo();
            }
            catch (Exception)
            {
                return Content(res.ModificationFailed + "<a href=\"/BlogAdmin/admin/AdminPublishWebConfig\">" + res.ContinueModify + "</a>", "text/html;charset=UTF-8");
            }
            return Content(res.ModifiedSuccessfully + " <a href=\"/BlogAdmin/admin/AdminPublishWebConfig\">" + res.ContinueModify + "</a>", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 站点基础设置
        /// </summary>
        public ActionResult AdminBaseConfig()
        {
            List<MyCheckBox> langList = new List<MyCheckBox>(); ;
            foreach (PageLang lang in WebUtils.GetLangList())
            {
                langList.Add(
                    new MyCheckBox { 
                        Text = lang.Key, 
                        Value = lang.Value,
                        IsChecked = Array.IndexOf(configinfo.WebLangList, lang.Value) > -1 ? true : false 
                    }
                    );
            }

            ViewBag.Langs = langList;

            List<SelectItem> themelst=new List<SelectItem>();
            themelst.Add(new SelectItem { Key = res.Default, Value = "" });
            DirectoryInfo di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("/Themes"));
            DirectoryInfo[] dirs = di.GetDirectories();
            for (int i = 0; i < dirs.Length; i++)
            {
                themelst.Add(new SelectItem { Key = dirs[i].Name, Value = dirs[i].Name });
            }
            ViewData["DefaultLang"] = new SelectList(WebUtils.GetLangList(), "Value", "Key", configinfo.DefaultLang);
            ViewData["Theme"] = new SelectList(themelst, "Value", "Key", configinfo.Theme);
            return View(configinfo);
        }

        /// <summary>
        /// 提交站点基础设置
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AdminBaseConfig(GeneralConfigInfo model)
        {
            try
            {
                GeneralConfigInfo config = configinfo;
                config.Weburl = model.Weburl;
                config.Webtitle = model.Webtitle;
                config.Icp = model.Icp;
                config.IndexPagerCount = model.IndexPagerCount;
                config.CatePagerCount = model.CatePagerCount;
                config.CommentPagerCount = model.CommentPagerCount;
                config.NotePagerCount = model.NotePagerCount;
                config.WebDescription = WebUtils.MyString(model.WebDescription).Replace("\r\n", "<br>");
                config.ThumbnailInfo = model.ThumbnailInfo;
                config.Theme = model.Theme;
                config.DefaultLang = model.DefaultLang;
                config.MaxSummaryCharCount = model.MaxSummaryCharCount;
                config.AdminEmail = model.AdminEmail;
                config.SmtpServer = model.SmtpServer;
                config.SmtpUser = model.SmtpUser;
                config.SmtpPass = model.SmtpPass;
                config.SmtpPort = model.SmtpPort;
                config.IfSendReplyEmail = model.IfSendReplyEmail;
                config.IfWebStatic = model.IfWebStatic;
                config.IfHtmlCreated = model.IfHtmlCreated;
                config.WebStaticFolderPart1 = model.WebStaticFolderPart1.Trim('/');
                config.WebStaticFolderPart2 = string.IsNullOrEmpty(model.WebStaticFolderPart2) ? "" : model.WebStaticFolderPart2.Trim();
                config.WebStaticFolder = config.WebStaticFolderPart1 + "/{lang}/" + config.WebStaticFolderPart2;
                config.WebLangList = model.WebLangList;
                config.UserPermission = model.UserPermission;
                config.IfValidateCode = model.IfValidateCode;
                config.Logo = model.Logo;

                WebUtils.ChangeTheme(model.Theme);
                CultureInfo cultureinfo = new CultureInfo(model.DefaultLang == "zh-cn" ? "" : configinfo.DefaultLang);
                System.Web.HttpContext.Current.Session["CurrentLanguage"] = cultureinfo;
                GeneralConfigs.Serialiaze(config, Server.MapPath(WebUtils.GetWebConfigPath()));
            }
            catch (Exception)
            {
                return Content(res.ModifyFailed + " <a href=\"/BlogAdmin/admin/AdminBaseConfig\">" + res.ContinueModify + "</a>", "text/html;charset=UTF-8");
            }
            return Content(res.ModifiedSuccessfully + " <a href=\"/BlogAdmin/admin/AdminBaseConfig\">" + res.ContinueModify + "</a>", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 更新js版本号
        /// </summary>
        [NonAction]
        public void RefreshConfigVersionNo()
        {
            GeneralConfigInfo config = configinfo;
            config.VersionNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            GeneralConfigs.Serialiaze(config, Server.MapPath(WebUtils.GetWebConfigPath()));
        }

        /// <summary>
        /// KE文件上传
        ///KindEditor 返回JSON格式说明： 
        ///格式：{"error":0,"message":".....","url":"/img/1111.gif"} 
        ///error：0成功，1失败，成功需要指定url值为图片/文件保存后的URL地址，如果error值不为0，则设置message值为错误提示信息 
        /// </summary>
        [HttpPost]
        public ActionResult UploadFile(string dir)
        {
            Hashtable hash = new Hashtable(); 
            string savePath = "/Content/Attached/";
            string saveUrl = configinfo.Weburl + "/Content/Attached/";
            int maxSize = 1000000; 
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
            switch (dir)
            {
                case "image":
                    savePath = "/Content/Upload/";
                    saveUrl = configinfo.Weburl + "/Content/Upload/";
                    break;
                case "flash":
                    break;
                case "media":
                    break;
                case "file":
                    break;
            }
            //获得上传文件
            HttpPostedFileBase file = Request.Files["imgFile"];
            //文件保存磁盘路径
            string dirPath = Server.MapPath(savePath);
            //文件名及后缀
            string fileName = file.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();
            if (file == null)
                return UploadJsonRe(1, res.UploadFile_Tip1, "");
            if (!Directory.Exists(dirPath))
                return UploadJsonRe(1, res.UploadFile_Tip2, "");
            if (file.InputStream == null || file.InputStream.Length > maxSize)
                return UploadJsonRe(1, res.UploadFile_Tip3, ""); 
            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dir]).Split(','), fileExt.Substring(1).ToLower()) == -1)
                return UploadJsonRe(1, res.UploadFile_Tip4, "");
            string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; 
            string filePath = dirPath + newFileName; 
            file.SaveAs(filePath); 
            string fileUrl = saveUrl + newFileName; 
            return UploadJsonRe(0, "", fileUrl);    
        }

        /// <summary>
        /// 上传返回提示
        /// </summary>
        private JsonResult UploadJsonRe(int error, string message, string url)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = error;
            hash["message"] = message;
            hash["url"] = url;
            return Json(hash, "text/html;charset=UTF-8"); 
        }

        /// <summary>
        /// 分类排序
        /// </summary>
        public ActionResult AdminCategorySort()
        {
            var lst = myService.getFCategoryList(" -- ");
            return View(lst);
        }

        /// <summary>
        /// 保存分类排序
        /// </summary>
        [HttpPost]
        public ActionResult AdminCategorySort(string ids)
        {
            List<CategoryModel> orderlst = new List<CategoryModel>();
            List<CategoryModel> newlst = new List<CategoryModel>();
            string[] arrId = ids.Trim(',').Split(',');
            for (int i = 0; i < arrId.Length; i++)
            {
                int orderid = i + 1;
                CategoryModel category = new CategoryModel();
                category = myService.GetCategoryByID(Utils.StrToInt(arrId[i]));
                category.OrderId = orderid.ToString();
                orderlst.Add(category);
            }
            GetNewCategoryList(orderlst, ref newlst, "0");
            SaveCateInfo(newlst);
            string re = "";
            var lst = myService.getFCategoryList(" -- ");
            foreach (CategoryModel c in lst)
            {
                string rootClass = c.ParentId == "0" ? " class=\"cl_root\"" : "";
                re += "<li id=\"" + c.CateId + "\"" + rootClass + ">" + c.CateName + " (" + c.CateId + ")</li>";
            }
            return Content(re, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 重置分类OrderStr
        /// </summary>
        private void GetNewCategoryList(List<CategoryModel> orderlst, ref List<CategoryModel> newlst, string parentId)
        {
            List<CategoryModel> tmplist = new List<CategoryModel>();
            foreach (CategoryModel c in orderlst)
            {
                if (c.ParentId == parentId)
                {
                    CategoryModel category = c;
                    category.OrderId = (newlst.Count() + 1).ToString();
                    newlst.Add(category);

                    if (Utils.StrToInt(c.SubCount) > 0)
                    {
                        GetNewCategoryList(orderlst, ref newlst, c.CateId);
                    }
                    continue;
                }
            }
        }

        /// <summary>
        /// 新增分类
        /// </summary>
        public ActionResult AdminCategoryAdd(int id)
        {
            ViewBag.CateId = id;
            ViewBag.CateName = id>0?myService.GetCategoryByID(id).CateName:"";
            ViewData["Type"] = new SelectList(WebUtils.GetTypeList(), "TypeId", "TypeName", 1);
            CategoryModel category = new CategoryModel();
            category.ParentId = id.ToString();
            if (id > 0)
                category.Type = myService.GetCategoryByID(id).Type;
            return View(category);
        }

        /// <summary>
        /// 新增分类
        /// </summary>
        [HttpPost]
        public ActionResult AdminCategoryAdd(CategoryModel model)
        {
            List<CategoryModel> newlst = new List<CategoryModel>();
            List<CategoryModel> catelist = myService.getFCategoryList();
            CategoryModel category = new CategoryModel();
            category.CateId = (myService.GetMaxCategoryID() + 1).ToString();
            category.CateName = model.CateName;
            category.IsIndex = model.IsIndex;
            category.IsNav = model.IsNav;
            category.ListNum = WebUtils.MyString(model.ListNum, "0");
            category.ParentId = model.ParentId;
            category.ReName = WebUtils.MyString(model.ReName);
            category.CustomView = WebUtils.MyString(model.CustomView);
            category.ReplyPermit = model.ReplyPermit;
            category.Status = model.Status;
            category.Type = model.Type;
            category.OrderId = (catelist.Count() + 1).ToString();
            category.SubCount = "0";
            category.Path = category.CateId;
            if (category.ParentId == "0")
            {
                catelist.Add(category);
                newlst = catelist;
            }
            else
            {
                catelist.Add(category);
                //刷新subcount,path值
                catelist = RefreshCateList(catelist);
                //重置顺序orderid
                GetNewCategoryList(catelist, ref newlst, "0");
            }
            SaveCateInfo(newlst);
            return Content(res.AddedSuccessfully + " <a href=\"/BlogAdmin/admin/AdminCategorySort\">" + res.View + "</a>", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 修改分类
        /// </summary>
        public ActionResult AdminCategoryEdit(int id)
        {
            CategoryModel category = myService.GetCategoryByID(id);
            ViewData["Type"] = new SelectList(WebUtils.GetTypeList(), "TypeId", "TypeName", category.Type);
            List<CategoryModel> list = myService.getFCategoryList("", "", " -- ").Where(m => m.Type == category.Type).Where(m => !("," + myService.GetCategoryIds(Utils.StrToInt(category.CateId)) + ",").Contains("," + m.CateId + ",")).ToList();
            list.Add(new CategoryModel { CateId="0",CateName="Root"});
            ViewData["ParentId"] = new SelectList(list, "CateId", "CateName", category.ParentId);
            return View(category);
        }

        /// <summary>
        /// 修改分类提交
        /// </summary>
        [HttpPost]
        public ActionResult AdminCategoryEdit(CategoryModel model)
        {
            List<CategoryModel> catelist = myService.getFCategoryList();
            List<CategoryModel> newlst = new List<CategoryModel>();
            List<CategoryModel> newlst2 = new List<CategoryModel>();
            CategoryModel category = new CategoryModel();
            category.CateId = model.CateId;
            category.CateName = model.CateName;
            category.IsIndex = model.IsIndex;
            category.IsNav = model.IsNav;
            category.ListNum =  WebUtils.MyString(model.ListNum, "0");
            category.ParentId = model.ParentId;
            category.ReName = WebUtils.MyString(model.ReName);
            category.CustomView = WebUtils.MyString(model.CustomView);
            category.ReplyPermit = model.ReplyPermit;
            category.Status = model.Status;
            category.Type = model.Type;
            category.OrderId = (catelist.Count() + 1).ToString();
            category.SubCount = "0";
            category.Path = "0";
            bool isPathChange=false;            
            foreach (CategoryModel c in catelist)
            {
                if (category.CateId == c.CateId)
                {
                    if (category.ParentId == c.ParentId)
                    {
                        category.OrderId = c.OrderId;
                        category.SubCount = c.SubCount;
                        category.Path = c.Path;
                    }
                    newlst.Add(category);
                }
                else
                    newlst.Add(c);
            }
            if (category.Path == "0")
            {
                isPathChange=true;
                //刷新subcount,path值
                newlst = RefreshCateList(newlst);
                //重置顺序orderid
                GetNewCategoryList(newlst, ref newlst2, "0");
            }
            else
            { newlst2 = newlst; }
            SaveCateInfo(newlst2);
            //分类层级关系改变时更新文章表里path信息
            if(isPathChange)
            {
                CategoryModel newcategory = myService.GetCategoryByID(Utils.StrToInt(model.CateId));
                myService.BatchUpdateArticlePath(Utils.StrToInt(model.CateId), newcategory.Path);
            }
            return Content(res.AddedSuccessfully + " <a href=\"/BlogAdmin/admin/AdminCategorySort\">" + res.View + "</a>", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        [HttpPost]
        public ActionResult AdminCategoryDel(int id)
        {
            List<CategoryModel> catelist = myService.getFCategoryList();
            List<CategoryModel> newlst = new List<CategoryModel>();
            List<CategoryModel> newlst2 = new List<CategoryModel>();
            foreach (CategoryModel c in catelist)
            {
                if (id.ToString() != c.CateId)
                { newlst.Add(c); }
            }
            GetNewCategoryList(newlst, ref newlst2, "0");
            newlst2 = RefreshCateList(newlst2);
            SaveCateInfo(newlst2);
            return Content(res.DeletedSuccessfully + " <a href=\"/BlogAdmin/admin/AdminCategorySort\">" + res.View + "</a>", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        public ActionResult AdminUserList(int? p)
        {
            int pageSize = 20;
            int totalRecords = 0;
            int pageno = p ?? 1;
            ViewBag.PageNo = pageno;
            MembershipUserCollection users = Membership.GetAllUsers();
            totalRecords = users.Count;
            ViewBag.PageCount = totalRecords / pageSize + (totalRecords % pageSize > 0 ? 1 : 0);
            var page = users.Cast<MembershipUser>().ToList().OrderByDescending(a => a.CreationDate).Skip(pageSize * (pageno-1)).Take(pageSize);
            return View(page);
        }

        /// <summary>
        /// 管理列表
        /// </summary>
        public ActionResult AdminManagerList()
        {
            var user = Roles.GetUsersInRole("Admin");
            return View(user);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpPost]
        public ActionResult AdminDelUser(string user)
        {
            try
            {
                Membership.DeleteUser(user);
            }
            catch (Exception)
            {
                return Content(res.DeleteFailed, "text/html;charset=UTF-8");
            }
            return Content(res.DeletedSuccessfully, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 用户从角色中删除
        /// </summary>
        [HttpPost]
        public ActionResult AdminRemoveUserFromRole(string user, string role = "Admin")
        {
            try
            {
                Roles.RemoveUserFromRole(user, role);
            }
            catch (Exception)
            {
                return Content(res.DeleteFailed, "text/html;charset=UTF-8");
            }
            return Content(res.DeletedSuccessfully, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 用户加入到角色
        /// </summary>
        [HttpPost]
        public ActionResult AdminAddUserToRole(string user, string role = "Admin")
        {
            try
            {
                Roles.AddUserToRole(user, role);
            }
            catch (Exception)
            {
                return Content(res.OperationFailed, "text/html;charset=UTF-8");
            }
            return Content(res.OperationSuccessful, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 页面整体生成
        /// </summary>
        public ActionResult AdminHtmlCreate()
        {
            List<PageLang> langList = new List<PageLang>();
            foreach (PageLang lang in WebUtils.GetLangList())
            {
                if (Array.IndexOf(configinfo.WebLangList, lang.Value) > -1)
                    langList.Add(lang);
            }
            langList.Insert(0, new PageLang
            {
                Key = res.Nolimited,
                Value = ""
            });
            ViewData["LangList"] = new SelectList(langList, "Value", "Key","");

            List<CategoryModel> catelist = myService.getFCategoryList("1", "", " -- ");
            catelist.Insert(0, new CategoryModel
            {
                CateId = "0",
                CateName = res.Nolimited
            });
            ViewData["CateId"] = new SelectList(catelist, "CateId", "CateName", 0);
            return View();
        }

        /// <summary>
        /// 页面批量生成
        /// </summary>
        [HttpPost]
        public ActionResult AdminHtmlBatchCreate(int cate,int dateRange,string from,string to)
        {
            List<ArticleItem> re = new List<ArticleItem>();
            try
            {
                string cids = cate.ToString();
                if (cate > 0)
                {
                    CategoryModel category = myService.GetCategoryByID(cate);
                    if (Utils.StrToInt(category.SubCount) > 0)
                    {
                        cids = myService.GetCategoryIds(cate);
                    }
                }
                if (cids == "0") { cids = ""; }
                var articles = myService.GetArticlesByDateRange(1, cids, 0, dateRange, from, to);
                
                foreach (blog_varticle varticle in articles)
                {
                    re.Add(
                        new ArticleItem { id = varticle.id, rename = varticle.rename,date=varticle.createdate.ToString("yyyy-MM-dd") }
                        );
                }
            }
            catch
            { }
            return Json(re, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 单个页面生成
        /// </summary>
        [HttpPost]
        public ActionResult AdminDoCreate(string date, string lang, int id, string rename)
        {
            try
            {
                WebUtils.CreateHtml(1,id,rename,lang,Convert.ToDateTime(date));
            }
            catch (Exception)
            {
                return Content("0", "text/html;charset=UTF-8");
            }
            return Content("1", "text/html;charset=UTF-8");
        }


        /// <summary>
        /// 保存站点信息
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AdminSiteInfo(SiteInfo model)
        {
            SiteInfo site = new SiteInfo();
            site.Logo = WebUtils.MyString(model.Logo);
            site.Description = WebUtils.MyString(model.Description);
            site.Name = configinfo.Webtitle;
            site.Url = configinfo.Weburl;
            site.Country = WebUtils.MyString(model.Country);
            site.Tags = WebUtils.MyString(model.Tags);
            

            if (ModelState.IsValid)
            {
                string operationtype = WebUtils.MyString(Request["OperationType"],"1");
                string str = "<html>\n";
                str += "<head>\n";
                str += "<title>" + site.Name + "</title>\n";
                str += "</head>\n";
                str += "<body>\n";
                str += "<div id=\"name\">" + site.Name + "</div>\n";
                str += "<div id=\"url\">" + site.Url + "</div>\n";
                str += "<img alt=\"" + site.Name + "\" src=\"" + site.Logo + "\"/>\n";
                str += "<div id=\"logo\">" + site.Logo + "</div><br/>\n";
                str += "<span id=\"pro\">" + site.Pro + "</span>\n";
                str += "<span id=\"version\">" + site.Version + "</span><br/>\n";
                str += "<div id=\"country\">" + site.Country + "</div>\n";
                str += "<div id=\"tags\">" + site.Tags + "</div>\n";
                str += "<div id=\"description\">" + Utils.RefreshImageUrl(site.Description,configinfo.Weburl) + "</div>\n";
                str += "</body>\n";
                str += "</html>";
                string file = System.Web.HttpContext.Current.Server.MapPath("/content/site.htm");
                using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
                {
                    writer.Write(str);
                }
                if (operationtype == "1")
                {
                    string errorRe = "<br/>"+res.OperationFailed1+"<br/>";
                    errorRe += "(1)"+res.NetworkFailure+"<br/>";
                    errorRe += "(2)" + res.NetworkNoAccessed + ":" + site.Url + "<br/><br/>";
                    errorRe += "<a href=\"/BlogAdmin/Admin\">" + res.Back + "</a><br/><br/><br/>";
                    string re = WebUtils.MyString(Utils.GetSourceTextByUrl(configinfo.YQHome + "?u=" + HttpUtility.UrlEncode(site.Url)), errorRe);
                    return Content(re, "text/html;charset=UTF-8");
                }
                return Content("1", "text/html;charset=UTF-8");
            }
            return Content("Error!", "text/html;charset=UTF-8");
        }
    }
}
